package com.test.thread.countdownlatch;

import java.util.concurrent.CountDownLatch;

/**
 * Created by jl on 2018/10/17 0017
 * 统一控制所有工人一起工作、一起下班
 */
public class Demo {

    static final class Worker implements Runnable {
        private CountDownLatch startSignal;
        private CountDownLatch doneSignal;

        public Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
            this.startSignal = startSignal;
            this.doneSignal = doneSignal;
        }


        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " ready for running ...");
            try {
                startSignal.await();
                // 开始工作
                System.out.println(Thread.currentThread().getName() + " is doing work ...");
                Thread.sleep(500);

                System.out.println(Thread.currentThread().getName() + " ready for work done ...");
                doneSignal.countDown();
                // 结束工作
                doneSignal.await();
                System.out.println(Thread.currentThread().getName() + " work done");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch startSignal = new CountDownLatch(1);
        CountDownLatch doneSignal = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {
            new Thread(new Worker(startSignal, doneSignal)).start();
        }

        Thread.sleep(1000);
        // 铃声一响，所有工人一起工作
        startSignal.countDown();
    }
}
